package com.ztools.mvp;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import com.ztools.mvp.proxy.MvpBindCallback;
import com.ztools.mvp.proxy.impl.ViewLifecycleCallbackProxy;


public abstract class BaseRelativeLayout<V extends IView, P extends IPresenter<V>> extends RelativeLayout implements MvpBindCallback<V, P> {
    private P p;
    private V v;
    private ViewLifecycleCallbackProxy<V, P> mLifecycleCallback;

    public ViewLifecycleCallbackProxy<V, P> getLifecycleCallback() {
        if (this.mLifecycleCallback == null) {
            this.mLifecycleCallback = new ViewLifecycleCallbackProxy<>(this);
        }
        return this.mLifecycleCallback;
    }

    public BaseRelativeLayout(Context context) {
        this(context, null);
    }

    public BaseRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BaseRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 初始化数据
     */
    protected abstract void init();

    @Override
    public P newPresenter() {
        return this.p;
    }

    @Override
    public V newMvpView() {
        return this.v;
    }

    @Override
    public P getPresenter() {
        return this.p;
    }

    @Override
    public void setPresenter(P p) {
        this.p = p;
    }


    @Override
    public V getMvpView() {
        return this.v;
    }

    @Override
    public void setMvpView(V v) {
        this.v = v;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        getLifecycleCallback().onMeasure();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        getLifecycleCallback().onLayout();
    }

    @Override
    protected void onAttachedToWindow() {
        getLifecycleCallback().onAttachedToWindow();
        super.onAttachedToWindow();

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getLifecycleCallback().onDetackedFromWindow();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        getLifecycleCallback().onSizeChanged();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        getLifecycleCallback().onDraw();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        getLifecycleCallback().onFinishInflate();
    }
}
